<template>
  <div class="alarm-popup">
    <div class="popup-header">
      <h3 class="popup-title">{{ currentAlarmInfo?.info?.alarmTitle || title || '预警信息' }}</h3>
      <button class="close-btn" @click="$emit('close')">
        <svg width="16" height="16" viewBox="0 0 16 16">
          <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
        </svg>
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="!currentAlarmInfo" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载预警信息...</p>
    </div>

    <!-- 报警内容 -->
    <div class="card-box" v-else>
      <el-row :gutter="10" v-if="currentAlarmInfo">
        <el-col :span="24">
          <el-descriptions :column="2" class="largeScreen-descriptions">
            <el-descriptions-item label="报警类型">{{ currentAlarmInfo.info.alarmTypeName }}</el-descriptions-item>
            <el-descriptions-item label="报警位置">{{ currentAlarmInfo.info.alarmAddr }}</el-descriptions-item>
            <el-descriptions-item label="报警次数">{{ currentAlarmInfo.info.alarmTotal }}</el-descriptions-item>
            <el-descriptions-item label="上报时间">{{ currentAlarmInfo.info.reportTime }}</el-descriptions-item>
            <el-descriptions-item label="报警开始时间">{{ currentAlarmInfo.info.alarmStartTime }}</el-descriptions-item>
            <el-descriptions-item label="最新报警时间">{{ currentAlarmInfo.info.alarmTime }}</el-descriptions-item>
            <el-descriptions-item label="报警持续时间">{{ currentAlarmInfo.info.duration }}</el-descriptions-item>
            <el-descriptions-item label="处置状态">
              <span>{{ currentAlarmInfo?.info?.statusName || '未知' }}</span>
              <el-button type="primary" size="small" @click="goAlarmWork" v-if="currentAlarmInfo?.info?.workOrderInfoUrl"> 查看报警工单 </el-button>
            </el-descriptions-item>
            <el-descriptions-item label="处置时间">{{ currentAlarmInfo?.info?.processTime || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="报警压力" v-if="isShowAlarmPressure">{{ alarmValue }}</el-descriptions-item>
            <el-descriptions-item label="经纬度" v-if="isShowLonLat">{{ formattedNumber }}</el-descriptions-item>
            <el-descriptions-item label="阈值最大值" v-if="currentAlarmInfo?.info?.thresholdMax">
              {{ currentAlarmInfo?.info?.thresholdMax + (currentAlarmInfo?.info?.unit || '') }}
            </el-descriptions-item>
            <el-descriptions-item label="阈值最小值" v-if="currentAlarmInfo?.info?.thresholdMin">
              {{ currentAlarmInfo?.info?.thresholdMin + (currentAlarmInfo?.info?.unit || '') }}
            </el-descriptions-item>
            <el-descriptions-item label="智能分析" v-if="currentAlarmInfo?.info?.alarmType == '01'">
              <el-button v-if="isShowIntelligentAnalyse" type="primary" size="default" @click="modelingHandle()">智能分析结果</el-button>
              <span v-else>模型暂无分析结果</span>
            </el-descriptions-item>
            <el-descriptions-item label="报警级别" v-if="currentAlarmInfo?.info?.alarmLevel"
              >{{ currentAlarmInfo?.info?.alarmLevel }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <el-row :gutter="10" v-if="currentAlarmInfo">
        <el-col :span="24">
          <div class="title">
            <el-row :gutter="10">
              <el-col :span="16" class="time-period">
                <span>{{ getAlarmTime }}{{ alarmTimePeriod }}</span>
              </el-col>
              <el-col :span="5" class="escalate-records">
                <span @click="ToggleOperatingData" v-if="currentAlarmInfo?.data && currentAlarmInfo?.overhaul">{{ OperationalDataName }}</span>
              </el-col>
              <el-col :span="3" class="escalate-records">
                <span @click="ReportHandle">报警记录</span>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <el-row v-if="currentAlarmInfo">
        <el-col :span="24">
          <div class="chart-box">
            <runData v-if="isShowECharts" :echartsData="currentAlarmInfo?.data" :deviceInfo="currentAlarmInfo?.info" />
            <el-empty v-else :image="empty" description="暂无数据" class="largeScreen-empty" />
          </div>
        </el-col>
      </el-row>
      <alarmRecords v-if="currentAlarmInfo" :overhaul="currentAlarmInfo?.overhaul" :info="currentAlarmInfo?.info" ref="alarmRecordsRef" />
      <EarlyWarningTickets ref="EarlyWarningTicketsRef" :alarm-work-order-url="EarlyWarningUrl" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue';
import dayjs from 'dayjs';
import runData from '@/components/ECharts/runData/index.vue';
import { getModelData, getPointInfo, configKey } from '@/api/earlyWarning';
import alarmRecords from '@/components/alarmRecords/index.vue';
import EarlyWarningTickets from '@/components/EarlyWarningTickets/index.vue';
import { useIntelligentAnalyticsStore } from '@/store/modules/IntelligentAnalytics/useIntelligentAnalyticsStore';
import router from '@/router';
import empty from '@/assets/icons/svg/empty-box.svg';
import { useAtlasStore } from '@/store/modules/atlas';
const emit = defineEmits<{
  close: [];
}>();
interface Props {
  data: any;
  title?: string;
}
const props = defineProps<Props>();
const currentAlarmInfo = ref<any>(null);
const isShowBtn = ref(false);
const alarmRecordsRef = ref();
const Someday = ref<string>('');
const alarmTimePeriod = ref('');
//根据报警级别获取报警事件
const getAlarmTime = computed(() => {
  if (!currentAlarmInfo.value?.info) return '设备运行数据监测';

  const data = currentAlarmInfo.value.info;
  if (data.alarmType == '05') {
    return '实时视频';
  } else {
    if (data.status == '3') {
      //这里面代表着已处置 时间就是开始时间到处置时间
      return `设备运行数据监测`;
    } else {
      //否则就是还没有处置完成的就是从开始时间到现在
      return `设备运行数据监测`;
    }
  }
});
// 监听报警级别变化 并通过报警时间 来渲染时间段
watch(
  () => currentAlarmInfo.value?.info,
  (newVal) => {
    if (!newVal) return;
    if (newVal.alarmType == '05') {
      alarmTimePeriod.value = '';
    } else {
      //这个判断是因为获取设备的运行数据之后 导致报警的时间消失了  所以判断 如果要是没有报警事件就直接return
      if (!newVal.reportTime && !newVal.processTime) return;
      if (newVal.status == '3') {
        alarmTimePeriod.value = `(${newVal.reportTime.slice(0, 10) + '至' + newVal.processTime.slice(0, 10)})`;
      } else {
        alarmTimePeriod.value = `(${newVal.reportTime.slice(0, 10) + '至' + dayjs(new Date().getTime()).format('YYYY-MM-DD')})`;
      }
    }
  },
  { immediate: true }
);
const ReportHandle = () => {
  alarmRecordsRef.value.open();
};
// 判断是否显示echarts
const isShowECharts = computed(() => {
  return currentAlarmInfo.value?.data && currentAlarmInfo.value.data?.data && currentAlarmInfo.value.data?.seriesList;
});
//格式化经纬度
const formattedNumber = computed(() => {
  if (!currentAlarmInfo.value?.info) return '';

  const lat = currentAlarmInfo.value.info.latitude;
  const lng = currentAlarmInfo.value.info.longitude;
  return `${lng},${lat}`;
});
const alarmValue = computed(() => {
  if (!currentAlarmInfo.value?.data?.data?.yaxisList || !currentAlarmInfo.value?.info) return 0;

  if (currentAlarmInfo.value.data?.data?.yaxisList?.[0]?.unit === 'Mpa') {
    return currentAlarmInfo.value.info.value / 1000000;
  } else {
    return currentAlarmInfo.value.info.value;
  }
});
const isShowAlarmPressure = computed(() => {
  return currentAlarmInfo.value?.info?.alarmType === '02';
});
const isShowLonLat = computed(() => {
  return currentAlarmInfo.value?.info?.latitude && currentAlarmInfo.value?.info?.longitude;
});
const isShowIntelligentAnalyse = computed(() => {
  return currentAlarmInfo.value?.info?.alarmType === '01' && isShowBtn.value;
});
//点击智能分析事件
const modelingHandle = () => {
  router.push('/IntelligentAnalytics');
};
//获取参数设置近某天的运行数据
const OperationalDataName = ref(`近${Someday.value}天运行数据`);
//切换运行数据
const ToggleOperatingData = () => {
  const params = {
    type: undefined,
    id: undefined
  };
  if (OperationalDataName.value === `近${Someday.value}天运行数据`) {
    OperationalDataName.value = `查看报警数据`;
    params.type = 'MONITOR';
    params.id = currentAlarmInfo.value?.overhaul?.id;
  } else {
    OperationalDataName.value = `近${Someday.value}天运行数据`;
    params.type = 'GAOJINGTYPE';
    params.id = currentAlarmInfo.value?.info?.id;
  }
  getPointInfo(params).then((res) => {
    currentAlarmInfo.value = {
      ...currentAlarmInfo.value,
      data: res.data.data
    };
  });
};
const EarlyWarningUrl = ref<string>('');
const EarlyWarningTicketsRef = ref();
//查询预警工单
const goAlarmWork = () => {
  if (currentAlarmInfo.value?.info?.workOrderInfoUrl) {
    EarlyWarningUrl.value = currentAlarmInfo.value.info.workOrderInfoUrl;
    EarlyWarningTicketsRef.value?.open();
  }
};
onMounted(async () => {
  try {
    const { data: PointData } = await getPointInfo({ type: props.data.type, id: props.data.id });
    currentAlarmInfo.value = PointData;
    const { data: SomedayData } = await configKey('n_day_run');
    Someday.value = SomedayData;
    const { data: ModelData } = await getModelData({ id: currentAlarmInfo.value?.info?.id });
    useIntelligentAnalyticsStore().modelData.value = ModelData;
    if (ModelData) {
      isShowBtn.value = true;
    }
  } catch (error) {
    console.log(error, '获取模型数据失败');
  }
});
</script>

<style scoped lang="scss">
.alarm-popup {
  background-image: url('@/assets/largescreen/xiangqing-kuang.png');
  background-size: 100% 100%;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  width: 800px;
  max-height: 700px;
  overflow: hidden;
  color: white;
  box-sizing: border-box;
  padding: 20px;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0 10px 0;
}

.popup-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #0be4f1;
}

.close-btn {
  background: none;
  border: none;
  color: #fff;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.2s;

  &:hover {
    background: rgba(255, 255, 255, 0.1);
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: white;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #0be4f1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.alarm-content {
  max-height: calc(85vh - 120px);
  overflow-y: auto;
}

.alarm-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.alarm-level {
  display: flex;
  align-items: center;
  gap: 12px;
}

.level-badge {
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 600;

  .level-critical & {
    background: rgba(220, 38, 38, 0.2);
    color: #dc2626;
    border: 1px solid rgba(220, 38, 38, 0.3);
  }

  .level-high & {
    background: rgba(239, 68, 68, 0.2);
    color: #ef4444;
    border: 1px solid rgba(239, 68, 68, 0.3);
  }

  .level-medium & {
    background: rgba(245, 158, 11, 0.2);
    color: #f59e0b;
    border: 1px solid rgba(245, 158, 11, 0.3);
  }

  .level-low & {
    background: rgba(34, 197, 94, 0.2);
    color: #22c55e;
    border: 1px solid rgba(34, 197, 94, 0.3);
  }

  .level-unknown & {
    background: rgba(156, 163, 175, 0.2);
    color: #9ca3af;
    border: 1px solid rgba(156, 163, 175, 0.3);
  }
}

.alarm-status {
  font-size: 12px;

  &.status-active {
    color: #ef4444;
  }

  &.status-resolved {
    color: #22c55e;
  }

  &.status-pending {
    color: #f59e0b;
  }

  &.status-unknown {
    color: #9ca3af;
  }
}

.alarm-time {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
}

.alarm-details {
  margin-bottom: 24px;
}

.alarm-descriptions {
  :deep(.el-descriptions__label) {
    color: rgba(255, 255, 255, 0.7);
    font-weight: 500;
  }

  :deep(.el-descriptions__content) {
    color: #fff;
  }
}

.alarm-message {
  margin-bottom: 24px;

  h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #0be4f1;
  }
}

.message-content {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  line-height: 1.6;
}

.risk-assessment {
  margin-bottom: 24px;

  h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #0be4f1;
  }
}

.risk-content {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.risk-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.risk-label {
  color: rgba(255, 255, 255, 0.7);
}

.risk-value {
  font-weight: 600;

  &.risk-critical {
    color: #dc2626;
  }

  &.risk-high {
    color: #ef4444;
  }

  &.risk-medium {
    color: #f59e0b;
  }

  &.risk-low {
    color: #22c55e;
  }

  &.risk-unknown {
    color: #9ca3af;
  }
}

.emergency-response {
  margin-bottom: 24px;

  h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #0be4f1;
  }
}

.response-content {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);

  ul {
    margin: 0;
    padding-left: 20px;

    li {
      margin-bottom: 8px;
      line-height: 1.6;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.related-data {
  margin-bottom: 24px;

  h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #0be4f1;
  }
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
}

.data-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  text-align: center;
}

.data-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 4px;
}

.data-value {
  font-size: 16px;
  font-weight: 600;
  color: #0be4f1;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.2);

  &:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: translateY(-1px);
  }

  &.primary {
    background: linear-gradient(45deg, #3b82f6, #6366f1);
    border: 1px solid rgba(59, 130, 246, 0.3);

    &:hover {
      background: linear-gradient(45deg, #2563eb, #4f46e5);
    }
  }
}

.card-box {
  min-width: 600px;
  min-height: 200px;
}

:deep(.largeScreen-descriptions) {
  .el-descriptions__label {
    color: rgba(255, 255, 255, 0.7);
    font-weight: 500;
  }

  .el-descriptions__content {
    color: #fff;
  }
}
</style>
<style scoped lang="scss">
.card-box {
  min-width: 700px;
  min-height: 200px;

  .title {
    background: url('@/assets/largescreen/title-pic.png') no-repeat center center;
    background-size: cover;
    width: 100%;
    height: 61px;
    line-height: 61px;
    padding-left: 20px;

    .time-period {
      color: white;
      font-family: PangMenZhengDao;
      font-size: 18px;
    }

    .escalate-records {
      color: #0be4f1;
      font-family: PangMenZhengDao;
      font-size: 18px;
      text-align: right;
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .chart-box {
    width: 700px;
    height: 280px;

    .video-box {
      width: 100%;
      height: 100%;
    }
  }

  .capacity-box {
    width: 100%;
    height: 50px;
    border: 2px dashed #ccc;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .capacity-value {
      font-weight: 700;
      font-size: 16px;
      color: #00ffff;
    }

    .capacity-title {
      font-size: 12px;
      color: #fff;
      opacity: 0.8;
    }
  }

  .empty-box {
    width: 100%;
    height: 50px;
    color: #0be4f1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
</style>
